import 'package:blog/locator.dart';
import 'package:blog/tools/list.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../api/api.dart';
import '../../../constants.dart';
import '../../../src/generated/models/article.pb.dart';
import '../../routes.dart';
import 'sidebar_container.dart';

class RecentArticles extends StatelessWidget{
  List<ArticleItem> articles = [];
  RecentArticles({
    Key? key, required this.articles
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> recentCards = ListTool.generateOrEmpty(articles, () => [], (ArticleItem item) => RecentPostCard(
      image: item.image,
      title: item.title,
      press: () => Get.toNamed(Routes.detailRoute(item.articleId.toString())),
    ));
    return SidebarContainer(
      title: "最新的文章",
      child: Column(
        children: ListTool.insertGap(recentCards, SizedBox(height: 10)),
      ),
    );
  }
}

class RecentPostCard extends StatelessWidget {
  final String image, title;
  final VoidCallback press;

  const RecentPostCard({
    Key? key,
    required this.image,
    required this.title,
    required this.press,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: press,
        child: Row(
          children: [
            Expanded(
              flex: 2,
              child: Image.network(
                image,
                errorBuilder:
                    (BuildContext ctx, Object obj, StackTrace? trace) =>
                        Image.asset("assets/images/logo.png"),
              ),
            ),
            SizedBox(width: kDefaultPadding),
            Expanded(
              flex: 5,
              child: Text(
                title,
                maxLines: 2,
                style: TextStyle(
                  color: kDarkBlackColor,
                  fontWeight: FontWeight.bold,
                  height: 1.5,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
